<template>
  <div>
    <h2>WebSocket 示例</h2>
    <input v-model="message" placeholder="输入消息" />
    <button @click="sendMessage">发送</button>
    <ul>
      <li v-for="msg in messages" :key="msg">{{ msg }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

let socket = null
const message = ref('')
const messages = ref([])

onMounted(() => {
  socket = new WebSocket('ws://localhost:8080/ws')

  socket.onopen = () => {
    console.log('WebSocket 连接成功')
  }

  socket.onmessage = (event) => {
    messages.value.push(event.data)
  }

  socket.onclose = () => {
    console.log('WebSocket 连接关闭')
  }
})

onUnmounted(() => {
  if (socket) {
    socket.close()
  }
})

const sendMessage = () => {
  if (socket && socket.readyState === WebSocket.OPEN) {
    socket.send(message.value)
    message.value = ''
  }
}
</script>
